<template>
  <div class="p-15 p-t-0">
    <div class="table-padding orderDialog">
      <el-form :model="modelForm" ref="modelForm">
        <div>
          <el-row>
            <el-col :span="7">
              <el-form-item prop="supplier" :rules="[]">
                <div class="el-input el-input-group el-input-group--prepend">
                  <div class="el-input-group__prepend">供应商名称</div>
                  <el-select v-model="modelForm.supplierName" size="medium" filterable placeholder="请选择供应商"
                             :disabled="true" style="width: 100%">
                    <el-option
                      v-for="item in suppliers"
                      :key="item.id"
                      :label="item.name"
                      :disabled="(item.state && item.state.key!='NORMAL')"
                      :value="item.id">
                    </el-option>
                  </el-select>
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="7" :offset="1">
              <el-form-item prop="no" :rules="[]">
                <div class="el-input el-input-group el-input-group--prepend">
                  <div class="el-input-group__prepend">订单日期</div>
                  <el-date-picker size="medium"
                                  v-model="modelForm.purchaseTime"
                                  type="date"
                                  style="width: 100%"
                                  format="yyyy-MM-dd"
                                  value-format="yyyy-MM-dd"
                                  placeholder="选择日期"
                                  :readonly="true"
                  >
                  </el-date-picker>
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="7">
              <el-form-item prop="no" :rules="[]">
                <div class="el-input el-input-group el-input-group--prepend">
                  <div class="el-input-group__prepend">发货日期</div>
                  <el-date-picker size="medium"
                                  v-model="modelForm.sendTime"
                                  type="date"
                                  style="width: 100%"
                                  format="yyyy-MM-dd"
                                  value-format="yyyy-MM-dd"
                                  placeholder="选择日期"
                  >
                  </el-date-picker>
                </div>
              </el-form-item>
            </el-col>
          </el-row>
        </div>
        <div class="orderTable">
          <el-form-item class="text-left text-left1">
            <el-button size="medium" class="m-l-0" type="success" @click="resetForm('modelForm')"><i
              class="icon icon-tijiao"></i> 确认发货
            </el-button>
            <!--<el-button size="medium" type="warning" v-if="modelForm.id" @click="printOrder"><i-->
            <!--class="icon icon-dayin"></i> 打印-->
            <!--</el-button>-->
            <el-button size="medium" type="danger" @click="goBack()"><i class="icon icon-fanhui1"></i> 取消</el-button>
          </el-form-item>

          <el-table
            :data="tableData"
            border
            show-summary
            :summary-method="getSummaries"
            style="width: 100%">
            <el-table-column
              type="index"
              width="50">
            </el-table-column>
            <el-table-column
              prop="code"
              label="原料编号"
             >
              <!--<template  slot-scope="scope">-->
                <!--<div style="position: relative">-->
                  <!--<el-select v-model="scope.row.code" :disabled="isEdit" remote @change="codeChange(scope.$index)"   :remote-method="remoteMethod"-->
                             <!--filterable="" allow-create placeholder="请输入原料编号">-->
                    <!--<el-option v-for="(item,index) in material" :disabled="(item.state && item.state.key!='NORMAL')" :key="index"-->
                               <!--:label="item.code" :value="item.no">-->
                      <!--<div style="width:100px;border-bottom:1px solid #c0c0c0;padding:5px 0px">-->
                        <!--{{item.value}}[{{item.purchaseUnit}}]-->
                      <!--</div>-->
                    <!--</el-option>-->
                  <!--</el-select>-->
                  <!--<span class="el-icon-more" @click="handleIconClick(scope.$index)"-->
                        <!--style="cursor: pointer;font-size: 10px;padding-right: 5px; position: absolute;right: 10px;top: 40%"></span>-->
                <!--</div>-->
              <!--</template>-->
            </el-table-column>
            <el-table-column
              prop="name"
              label="原料名称"
              >
            </el-table-column>
            <el-table-column
              prop="spec"
              label="规格型号"
              >
            </el-table-column>
            <el-table-column
              prop="purchaseSpec"
              label="采购规格"
              >
            </el-table-column>
            <el-table-column
              prop="unitName"
              label="采购单位"
              >
            </el-table-column>
           <!-- <el-table-column
              prop="count"
              label="采购数量"
              >
            </el-table-column>-->
            <el-table-column
              prop="sendCount"
              label="发货数量"
              width="100">
              <template  slot-scope="scope">
                <el-input v-model="scope.row.sendCount" :disabled="isEdit" @blur="priceValidate(scope.row,'sendCount')" @focus="printNum()"
                          placeholder="0.00"></el-input>
              </template>
            </el-table-column>
            <el-table-column
              prop="sendPrice"
              label="发货单价"
              width="100">
              <template  slot-scope="scope">
                <el-input v-model="scope.row.sendPrice" :disabled="isEdit" @blur="priceValidate(scope.row,'sendPrice')" @focus="printNum()"
                          placeholder="0.00"></el-input>
              </template>
            </el-table-column>
            <el-table-column
              prop="historyPrice"
              label="历史采购单价"
              width="150">
              <template  slot-scope="scope">
                <span>{{scope.row.historyPrice | money}}</span>
              </template>
            </el-table-column>
            <el-table-column
              prop="money"
              label="发货金额"
              width="100">
              <template  slot-scope="scope">
                {{scope.row.money}}
               <!-- <el-input v-model="scope.row.money" :disabled="isEdit" @blur="priceValidate(scope.row,'money')"  @focus="printNum()"
                          placeholder="0.00"></el-input>-->
              </template>
            </el-table-column>

            <el-table-column
              prop="stockId"
              label="扣减仓库"
              width="100">
              <template  slot-scope="scope">
                <el-select v-model="scope.row.stockId" style="width: 100%;" @change="stockChange(scope.$index)">
                  <el-option v-for="item in scope.row.warehouses" :key="item.warehouse_id" :label="item.warehouse_name" :value="item.warehouse_id">
                  </el-option>
                </el-select>
              </template>
            </el-table-column>

            <el-table-column
              prop="stockCount"
              label="仓库库存"
              width="100">
              <template  slot-scope="scope">
                  {{scope.row.stockCount}}
              </template>
            </el-table-column>

            <el-table-column
              prop="memo"
              label="总部备注">
              <template  slot-scope="scope">
                <el-input v-model="scope.row.memo" :disabled="isEdit" placeholder=""></el-input>
              </template>
            </el-table-column>
            <el-table-column
              prop="memo"
              label="门店备注">
              <template  slot-scope="scope">
                {{scope.row.branchRemark}}
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-form>
    </div>
    <!--<materials-select :isShow="dialogTableVisible"  v-on:pushData="getData" v-on:closeDialog="dialogTableVisible=false"></materials-select>-->
  </div>
</template>
<script>
  //注意路径
  import materialsSelect from "@/components/materialsSelect.vue"
  export default {
    data() {
      return {
        dialogTableVisible: false,
        isEdit: false,
        type:1,
        tableData: [{
          id: "",
          code: '',
          name: '',
          goodsSpec: '',
          purchaseSpec: '',
          unitName: '',
          count: '0',
          price: '0.00',
          historyPrice: '',
          money: '0.00',
          memo: '',
          sendCount:"0.00",
          sendPrice:"0.00",
          warehouses:[],
          stockId:'',
          stockName:''
        }

          ],

        modelForm: {
          createAt:""
        },
        currentPage3:3,
        pageSizeSet: window.pageSizes,
        pageSize: window.pageSize,
        pageTotal: 10,
        material: [],
        supplier: "",
        content: "",
        warehouse: "",
        suppliers: [],
        warehouses: [],
        restaurants: [],
        timeout: null,
        gridData: [],
        itemActive: 0,
        data: [],
        selectRow: [],
        inputText: "",
        defaultProps: {
          children: 'children',
          label: 'label'
        },
        pickerOptions0: {
          disabledDate(time) {
            return time.getTime() < Date.now() - 8.64e7;
          }
        },
      }
    },
    components: {
      materialsSelect
    },
    created() {
      window.this = this;
      window.isload = true;
      this.initData();
    },
    mounted() {
      if (this.$route.query.type != null && this.$route.query.type != "") {
        if (this.$route.query.type == "5") {//5 说明是查看
          $("input").attr("disabled", true);
          $(".text-left1").css("display", "none");
          $(".text-left5").css("display", "block");
          this.isEdit = true;
        }
      }
    },
    methods: {
      stockChange(index){
        console.log(this.tableData[index].stockId);
        console.log(index);
        if(this.tableData[index].warehouses && this.tableData[index].warehouses.length>0){
          for(var i=0;i<this.tableData[index].warehouses.length;i++){
            if(this.tableData[index].warehouses[i].warehouse_id = this.tableData[index].stockId){
              this.tableData[index].stockName = this.tableData[index].warehouses[i].warehouse_name;
              this.tableData[index].stockCount = this.tableData[index].warehouses[i].count;
            }
          }
        }
        console.log( this.tableData[index].stockName)
      },
      //页面第一次进来获取表单需要的数据
      initData() {
        var id = this.$route.query.id;
        var query = "";
        if (id != null && id != "") {
          query = "?id=" + id;
          this.modelForm.id = id;
        }
        this.$axios.get("branchstores/branchPurchaseOrders/create" + query).then((data)=> {
          if (data.status == 200) {
            let json = data.content;
            //初始化单据到表单
            this.modelForm = json.branchPurchaseOrder;
            this.modelForm.sendTime=this.moment().format("YYYY-MM-DD");
            if (id != null && id != "") {
              this.material=json.materials;
              for (var i = 0; i < json.detailList.length; i++) {
                for(var j=0;j<json.materials.length;j++){
                  if(json.detailList[i].specId==json.materials[j].label){
                    json.detailList[i].purchaseNewPrice=json.materials[j].purchaseNewPrice;
                  }
                }
                json.detailList[i].detailId = json.detailList[i].id;
                json.detailList[i].code = json.detailList[i].no;
                json.detailList[i].unitName = json.detailList[i].purchaseUnit;
                json.detailList[i].purchaseSpec = json.detailList[i].purchaseSpec;
                json.detailList[i].spec = json.detailList[i].materialSpec;
                json.detailList[i].id = json.detailList[i].specId ;
                json.detailList[i].name = json.detailList[i].name ;
                json.detailList[i].memo = json.detailList[i].groupRemark ;
                json.detailList[i].sendCount = json.detailList[i].purchaseCount;
                json.detailList[i].sendPrice = (json.detailList[i].purchasePrice * 1).toFixed(2); //采购单价
                json.detailList[i].money = (json.detailList[i].sendCount*json.detailList[i].sendPrice * 1).toFixed(2); //采购金额

              }
              this.tableData = json.detailList;
            }
          } else {
            this.$message.error(data.message);
          }
        })
      },
      checkboxInit(row, index) {
        if (row.state && row.state.key != "NORMAL") {
          return 0;//不可勾选
        } else {
          return 1;
        }
      },
      handleClose(done){
        this.$emit('close');
        done();
      },
      /* 打印单据 */
      printOrder() {
        // 打印预览
        var $this = this;
        setTimeout(function () {
          $this.Print($this.$refs.printData);
        }, 200);
      },

      printNum(){
        event.currentTarget.select();
      },
      handleIconClick(index) {
        if (this.isEdit) {
          return;
        }
        this.dialogTableVisible = true;
        this.itemActive = index;
      },
      selectGood(page) {
        this.dialogTableVisible = true;
      },
      handleSizeChange(val) {
        this.pageSize = val;
        this.selectGood("");
      },
      handleNodeClick(data) {
        var id = data.id;
        this.content = "search.category.id_eq=" + id + "";
        this.selectGood("");
      },
      newLabel(newList) {
        if (newList) {
          for (var i = 0; i < newList.length; i++) {
            newList[i].label = newList[i].name;
            if (newList[i].children) {
              this.newLabel(newList[i].children)
            }
          }
        }
      },
      goBack() {
        this.router.go(-1);
      },
      getSummaries(param) {
        const {columns, data} = param;
        const sums = [];
        columns.forEach((column, index) => {
          if (index === 0) {
            sums[index] = '合计';
            return;
          }
          if (index == 6 || index == 7 || index ==9) {
            const values = data.map(item => Number(item[column.property]));
            if (!values.every(value => isNaN(value))) {
              sums[index] = values.reduce((prev, curr) => {
                const value = Number(curr);
                if (!isNaN(value)) {
                  if (index == 7) {
                    return prev + curr;
                  } else {
                    return ((prev * 1 + curr * 1) * 1).toFixed(2);
                  }
                } else {
                  if (index == 7) {
                    return prev;
                  } else {
                    return (prev * 1).toFixed(2);
                  }

                }
              }, 0);
            } else {
              sums[index] = '数据异常';
            }
          }
        });

        return sums;
      },
      submitForm(formName) {
        //console.log(this.tableData)
        this.type = 1;
        this.validateData(formName);
      },
      resetForm(formName) {
        this.type = 3;
        this.validateData(formName);
      },
      validateData(fromName) {
        for (var i = 0; i < this.tableData.length; i++) {
          if (this.tableData[i].id == "") {
            if (this.tableData.length == 1) {
              this.$message.error("请添加单据明细！");
              return;
            }
            this.tableData.splice(i, 1);
            i--;
          }
          if (this.tableData[i].sendCount <= 0) {
            this.$message.error("数量不能小于1！请检查第" + (i + 1) + "行数据");
            return;
          }
          if (!this.tableData[i].stockId || this.tableData[i].stockId=='') {
            this.$message.error("出库仓库不能为空！请检查第"+(i+1)+"行数据");
            return;
          }

        }
        if (this.tableData == null || this.tableData.length == 0) {
          this.$message.error("请添加单据明细！");
          return;
        }
        if (this.$route.query.type == "4") {//5 说明是查看
          this.modelForm.id = "";
        }
        this.$refs[fromName].validate((valid) => {
          if (valid) {
            var data = {};
            for(var i=0;i<this.warehouses.length;i++){
              if(this.modelForm.warehouseId==this.warehouses[i].id){
                this.modelForm.warehouseName=this.warehouses[i].name
              }
            }
            data.type=3;
            data.purchaseOrder = this.modelForm;
            var tempData=[];
            console.log(this.tableData);
            for(let i=0;i<this.tableData.length;i++){
              tempData.push({
                specId:this.tableData[i].id,
                no:this.tableData[i].code,
                name:this.tableData[i].name,
                materialId:this.tableData[i].materialId,
                purchaseSpec:this.tableData[i].purchaseSpec,
                purchaseUnit:this.tableData[i].unitName,
                purchaseCount:this.tableData[i].purchaseCount,
                purchasePrice:this.tableData[i].purchasePrice,
                purchaseNewPrice:this.tableData[i].purchaseNewPrice,
                amount:this.tableData[i].money,
                groupRemark:this.tableData[i].memo,//总部备注
                branchRemark:this.tableData[i].branchRemark,
                materialSpec:this.tableData[i].spec,
                stockUnit:this.tableData[i].stockUnit,
                sendCount:this.tableData[i].sendCount,
                sendPrice:this.tableData[i].sendPrice,
                stockId:this.tableData[i].stockId,
                stockName:this.tableData[i].stockName,
                uuid:this.tableData[i].uuid
              })
            }
            data.details = tempData;
//            console.log(data);
//            return;
            this.$axios.post("branchstores/branchPurchaseOrders/create", data, "json").then((data)=> {
              if (data.status == 200) {
                this.$message({
                  message: data.message,
                  type: 'success'
                });
                this.$emit('addSuccess');
                this.router.push({path: "/storePurchaseOrders"});
              } else {
                this.$message.error(data.message);
              }
            })
          } else {
            this.$message.error("请检查输入项");
            return false;
          }
        });
      },
      priceValidate(item, key) {
        console.log(item[key]);
        var isNum = /^(([1-9][0-9]*)|(([0]\.\d{1,2}|[1-9][0-9]*\.\d{1,2})))$/;
        if (!isNum.test(item[key])) {
          item[key] = "0.00"
        } else {
          item[key] = item[key]
        }
        switch (key) {
          case "sendCount":
            if (!isNaN(item.sendCount)) {
              item.money = item.sendPrice * item.sendCount;
              item.money = item.money.toFixed(2);
            } else {
              item.sendCount = 0
            }
            break;
          case "sendPrice":
            if (!isNaN(item.sendPrice)) {
              item.money = item.sendPrice * item.sendCount;
              item.money = item.money.toFixed(2);
              item.sendPrice = (item.sendPrice * 1).toFixed(2);
            } else {
              item.sendPrice = '0.00';
            }
            break;
          case "money":
            if (!isNaN(item.money) && item.sendCount > 0) {
              item.sendPrice = item.money / item.sendCount;
              item.sendPrice = item.sendPrice.toFixed(2);
              item.money = (item.money * 1).toFixed(2);
            } else {
              item.money = '0.00';
            }
            break;
        }
      },
      handleCurrentChange(item) {
        this.currentPage3 = item;
        this.selectGood(item);
      },
      addColumn(index) {
        if (this.isEdit) {
          return;
        }
        this.tableData.splice(index + 1, 0, {
          id: '',
          code: '',
          name: '',
          goodsSpec: '',
          purchaseSpec: '',
          unitId: '',
          unitName: '',
          count: '0',
          price: '0.00',
          historyPrice: '',
          money: '0.00',
          memo: '',
        })
      },
      minusColumn(index) {
        if (this.isEdit) {
          return;
        }
        if (this.tableData.length > 1) {
          this.tableData.splice(index, 1);
        } else {
          this.$message.info("最少保留一条");
        }
      },
      handleSelect(item, index) {
        //console.log(this.tableData[index])
      },
    }

  }
</script>
<style scoped>
  .el-form-item {
    margin-bottom: 10px !important;
  }

  .el-table tr {
    border-bottom: 1px solid #dfe6ec !important;
  }

  .text-left5 {
    display: none;
  }

  /*单据打印*/
  :root {
    --zoomsize: 60%;
    --line-height-set: 30px;
  }

  .print-con {
    zoom: 60%;
    width: 98%;
    color: #333333;
    font-size: 12px !important;
    background-color: #ffffff;
    padding: 0 10px;
    position: absolute;
    left: 0;
    top: 0;
    z-index: -10;
  }

  /*单据-标题*/
  .print-con .order-title {
    zoom: var(--zoomsize);
    font-size: 12px;
    font-weight: bold;
    text-align: center;
    padding: 5px;
    border-bottom: 2px solid #333333;
  }

  /*单据-说明信息*/
  .print-con .order-info {
    padding: 0;
    font-size: 10px !important;
    height: auto;
    overflow: hidden;
  }

  .print-con .order-info ul {
    height: auto;
    overflow: hidden;
    margin: 0;
    padding: 0;
  }

  .print-con .order-info ul li {
    list-style: none;
    font-size: 12px;
  }

  .print-con .order-info ul li {
    zoom: var(--zoomsize);
    float: left;
    width: 33%;
    height: var(--line-height-set);
    line-height: var(--line-height-set);
    overflow: hidden;
  }

  .print-con .order-info ul li.sigle-line {
    zoom: var(--zoomsize);
    width: 100%;
    display: block;
  }

  /*单据-商品列表*/
  .print-con .tb-con {
    widht: 100%;
    background-color: #b4b4b4;
    border: 1px solid #b4b4b4;
  }

  .print-con .tb-con th {
    zoom: var(--zoomsize);
    height: var(--line-height-set);
    line-height: var(--line-height-set);
    background-color: #ffffff;
    border: 1px solid #b4b4b4;
    font-size: 12px;
  }

  .print-con .tb-con td {
    zoom: var(--zoomsize);
    height: var(--line-height-set);
    line-height: var(--line-height-set);
    text-align: center;
    background-color: #ffffff; /*border: 1px solid #b4b4b4;*/
    font-size: 12px;
  }

  /*责任条款*/
  .print-con .item-info {
  }

  .print-con .item-info ul {
    margin: 0;
    padding: 0;
    list-style: none;
  }

  .print-con .item-info ul li {
    zoom: var(--zoomsize);
    height: var(--line-height-set);
    line-height: var(--line-height-set);
    font-size: 12px;
  }

</style>
